package com.qhgrain.api.menurolepermission.provider;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.ws.rs.core.Response;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.paas.base.modules.utils.date.DateUtil;
import com.paas.base.modules.utils.lang.StringUtil;
import com.pubframework.common.vo.RestVo;
import com.qhgrain.api.menurolepermission.entity.Role;
import com.qhgrain.api.menurolepermission.entity.RolePermission;
import com.qhgrain.api.menurolepermission.info.RoleInfo;
import com.qhgrain.api.menurolepermission.service.IRolePermissionService;
import com.qhgrain.api.menurolepermission.service.IRoleService;
import com.qhgrain.gway.util.UUIDUtil;

@Service
public class RoleServiceProvider implements com.qhgrain.api.menurolepermission.IRoleService{

	@Autowired
	private IRoleService roleServiceImpl;
	
	@Autowired
	private IRolePermissionService rolePermissionServiceImpl;
	
	@Override
	public Response add(String roleName, String roleType, String status,String createDate,String roleCode) {
		RestVo vo=new RestVo();
		try {
			//roleCode唯一
			if(StringUtil.isBlank(roleCode)){
				vo.setFail("roleCode不能为空");
			}else{
				Role r = this.roleServiceImpl.findByRoleCode(roleCode);
				if(r != null){
					vo.setFail("roleCode不能重复");
				}else{
					if(StringUtil.isBlank(createDate)){
						createDate = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
					}
					String id = UUIDUtil.getUUID();
					Role role = new Role(id,roleName,roleType,status,roleCode,createDate);
					this.roleServiceImpl.addRole(role);
					vo.setSuccess(id);
				}
			}
			
		} catch (Exception e) {
			vo.setFail(e.getMessage());
		}
		return Response.ok(vo).build();
	}

	@Override
	public Response edit(String roleId, String roleName, String roleType,
			String status,String roleCode) {
		RestVo vo=new RestVo();
		try {
			Role role = this.roleServiceImpl.getRoleById(roleId);
			if(role == null){
				vo.setFail("根据roleId对应的角色不存在");
			}else{
				//roleCode唯一
				if(StringUtil.isBlank(roleCode)){
					vo.setFail("roleCode不能为空");
				}else{
					Role r = this.roleServiceImpl.findByRoleCode(roleCode);
					if(r != null && !r.getId().equals(role.getId())){
						vo.setFail("roleCode不能重复");
					}else{
						role.setName(roleName);
						role.setType(roleType);
						role.setStatus(status);
						role.setRoleCode(roleCode);
						this.roleServiceImpl.editRole(role);
						vo.setSuccess("");
					}
				}
			}
			
		} catch (Exception e) {
			vo.setFail(e.getMessage());
		}
		
		return Response.ok(vo).build();
	}



	@Override
	public Response getRole(String roleId) {
		RestVo vo=new RestVo();
		try {
			Role role=roleServiceImpl.getRoleById(roleId);
			if(role == null){
				vo.setFail("根据roleId对应的角色不存在");
			}else{
				vo.setSuccess(role);
			}
			
		} catch (Exception e) {
			vo.setFail(e.getMessage());
		}
		return Response.ok(vo).build();
	}

	@Override
	public Response queryPage(String roleName, String roleType,
			String status, String page, String pageSize) {
		RestVo vo=new RestVo();
		try {
			PageInfo<Role> pageInfo = this.roleServiceImpl.queryPage(roleName, roleType, status, Integer.parseInt(page), Integer.parseInt(pageSize));
			JSONObject json = new JSONObject();
			json.put("list", pageInfo.getList());
			json.put("totalCount", pageInfo.getTotal());
			json.put("totalPage", pageInfo.getPages());
			
			vo.setSuccess(json);
		} catch (Exception e) {
			vo.setFail(e.getMessage());
		}
		return Response.ok(vo).build();
	}

	@Override
	public Response delete(String ids) {
		RestVo vo=new RestVo();
		try {
			String [] idArray=ids.split(",");
			this.roleServiceImpl.deleteByIds(idArray);
			vo.setSuccess("");
		} catch (Exception e) {
			vo.setFail(e.getMessage());
		}
		return Response.ok(vo).build();
	}

	@Override
	public Response grantPermissions(String addPermissionIds,String deletePermissionIds, String roleId) {
		RestVo vo=new RestVo();
		try {
			List<String> addIds = null;
			List<String> deleteIds = null;
			if(StringUtil.isNotBlank(addPermissionIds) && !"null".equalsIgnoreCase(addPermissionIds)){
				addIds = Arrays.asList(addPermissionIds.split(","));
			}
			if(StringUtil.isNotBlank(deletePermissionIds) && !"null".equalsIgnoreCase(deletePermissionIds)){
				deleteIds = Arrays.asList(deletePermissionIds.split(","));
			}
			this.rolePermissionServiceImpl.addAndDelete(roleId, addIds, deleteIds);
			vo.setSuccess("");;
		} catch (Exception e) {
			vo.setFail(e.getMessage());
		}

		return Response.ok(vo).build();
	}

	
	@Override
	public Response getPermission(String roleId,String appId) {
		RestVo vo=new RestVo();
		try {
			List<RolePermission> rps=this.rolePermissionServiceImpl.queryByRoleId(roleId,appId);
			List<String> list = new ArrayList<String>();
			for(RolePermission p: rps){
				list.add(p.getPermissionId());
			}
			vo.setSuccess(list);
		} catch (Exception e) {
			vo.setFail(e.getMessage());
		}
		
		return Response.ok(vo).build();
	}

	@Override
	public Response getAll(String userId) {
		RestVo vo=new RestVo();
		try {
			vo.setSuccess(this.roleServiceImpl.getAll(userId));
		} catch (Exception e) {
			vo.setFail(e.getMessage());
		}

		return Response.ok(vo).build();
	}
	@Override
	public Response grantUsers(String roleId, String userIds) {
		RestVo vo = new RestVo();
		try {
			// 多个角色，则是为单个用户分配多个角色
			if (StringUtils.isNotBlank(roleId) && roleId.contains(",")) {
				List<String> list = Arrays.asList(roleId.split(","));
				this.roleServiceImpl.grantRolesForUser(list, userIds);
			} else {// 否则是为多个用户分配一个角色
				List<String> list = Arrays.asList(userIds.split(","));
				this.roleServiceImpl.grantUsers(roleId, list);
			}
			vo.setSuccess("");
			;
		} catch (Exception e) {
			vo.setFail(e.getMessage());
		}

		return Response.ok(vo).build();
	}

	@Override
	public Response deleteUserRole(String roleId, String userIds) {
		RestVo vo = new RestVo();
		try {

			this.roleServiceImpl.deleteUserRole(roleId, userIds);

			vo.setSuccess("");
		} catch (Exception e) {
			vo.setFail(e.getMessage());
		}

		return Response.ok(vo).build();
	}

	

	@Override
	public Response getByRoleCode(String roleCode) {
		RestVo vo = new RestVo();
		try {
			if(StringUtil.isBlank(roleCode)){
				vo.setFail("roleCode不能为空");
			}else{
				vo.setSuccess(this.roleServiceImpl.findByRoleCode(roleCode));
			}
		} catch (Exception e) {
			vo.setFail(e.getMessage());
		}

		return Response.ok(vo).build();
	}

	public Response syncRoles(String operationType,String roleList) {
		RestVo vo = new RestVo();
		try {
			if(StringUtil.isBlank(operationType) || StringUtil.isBlank(roleList)){
				vo.setFail("operationType和roleList不能为空");
			}else{
				List<RoleInfo> list = JSONArray.parseArray(roleList, RoleInfo.class);
				if("insert".equalsIgnoreCase(operationType)){
					this.roleServiceImpl.insertBatch(list);
					vo.setSuccess("");
				}else if("modify".equalsIgnoreCase(operationType)){
					this.roleServiceImpl.update(list);
					vo.setSuccess("");
				}else if("delete".equalsIgnoreCase(operationType)){
					List<String> ids = new ArrayList<String>();
					if(list != null && list.size() > 0){
						for(RoleInfo r : list){
							ids.add(r.getId());
						}
						if(ids.size() > 0){
							this.roleServiceImpl.deleteByIds(StringUtils.join(ids,",").split(","));
						}
					}
					vo.setSuccess("");
				}else{
					vo.setFail("operationType不是insert/modify/delete中的一种");
				}
			}
			
		} catch (Exception e) {
			vo.setFail(e.getMessage());
		}

		return Response.ok(vo).build();
	}

	@Override
	public Response getRolesByAppId(String appId) {
		RestVo vo = new RestVo();
		try {
			if(StringUtil.isBlank(appId)){
				vo.setFail("appId不能为空...");
			}else{
				vo.setSuccess(this.roleServiceImpl.getRolesByAppId(appId));
			}
		} catch (Exception e) {
			vo.setFail(e.getMessage());
		}
		return Response.ok(vo).build();
	}

}
